package com.xiong.util;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class ClassScanner {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String packageName = "com.xiong"; // 指定包路径
        List<Class<?>> classes = scanClasses(packageName);

        for (Class<?> clazz : classes) {
            System.out.println(clazz.getName());
        }
    }

    public static List<Class<?>> scanClasses(String packageName) throws IOException, ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<>();

        String packagePath = packageName.replace('.', '/');
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        Enumeration<URL> resources = classLoader.getResources(packagePath);
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();

            if (resource.getProtocol().equals("file")) {
                String path = resource.getPath();
                addClassesFromDirectory(packageName, path, classes);
            }
        }

        return classes;
    }

    private static void addClassesFromDirectory(String packageName, String directory, List<Class<?>> classes) throws ClassNotFoundException {
        File file = new File(directory);

        if (file.exists() && file.isDirectory()) {
            File[] files = file.listFiles();

            if (files != null) {
                for (File child : files) {
                    if (child.isDirectory()) {
                        String childPackageName = packageName + "." + child.getName();
                        String childDirectory = child.getAbsolutePath();
                        addClassesFromDirectory(childPackageName, childDirectory, classes);
                    } else if (child.getName().endsWith(".class")) {
                        String className = packageName + "." + child.getName().replaceAll(".class$", "");
                        Class<?> clazz = Class.forName(className);
                        classes.add(clazz);
                    }
                }
            }
        }
    }
}
